package edu.java.water.controller;

import com.github.wxpay.sdk.WXPay;
import edu.java.water.entity.*;
import edu.java.water.service.*;
import edu.java.water.tool.GetWeChat;
import edu.java.water.tool.MyWXConfig;
import edu.java.water.tool.UUID;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class WXApiController {
    @Autowired
    private UserService userService;
    @Autowired
    private BuildingService buildingService;
    @Autowired
    private ProductNormService productNormService;
    @Autowired
    private NormService normService;
    @Autowired
    private CartService cartService;

    @RequestMapping("**")
    @ResponseBody
    public String index(){
        return "<h1 align='center' style='margin:20px 0 0 0'>欢迎来到water，该网站不提供任何服务</h1>";
    }

    /**
     *  用户信息获取
     * @param code 微信登录时授予的code
     * @return
     */
    @RequestMapping("/getUserOpenId")
    @ResponseBody
    public Map getUserOpenId(String code){
        GetWeChat openId = new GetWeChat();
        String open=openId.getOpenId(code);
        Map map = new HashMap();
        //读取用户信息
        UserEntity userEntity = userService.selectUserOpenId(open);
        if(userEntity==null){
            map.put("state",0);
            map.put("openId",open);
            return map;
        }
        map.put("state",1);
        JSON user = JSONObject.fromObject(userEntity);
        map.put("user",user);
        return map;
    }

    /**
     * 用户注册
     * @param openId 用户的ID
     * @param username 用户的昵称
     * @return
     */
    @RequestMapping("/setUser")
    @ResponseBody
    public Map setUser(String openId,String username){
        Map map = new HashMap();
        if(openId!=null && username!=null){
            boolean insert = userService.InsertUser(openId,username);
            if (insert){
                map.put("state",1);
                map.put("openid",openId);
                map.put("username",username);
                return map;
            }
        }
        map.put("state",0);
        return map;
    }

    /**
     * 获取数据库的地址信息
     * @return
     */
    @RequestMapping("/getBuilding")
    @ResponseBody
    public Map getBuilding(){
        Map map = new HashMap();
        List<BuildingEntity> buildingEntityList = buildingService.getBuilding();
        map.put("state",1);
        JSON building = JSONArray.fromObject(buildingEntityList);
        map.put("building",building);
        return map;
    }

    /**
     * 用户信息更新
     * @param userEntity 用户的信息
     * @return
     */
    @RequestMapping("/setUserData")
    @ResponseBody
    public Map setUserData(UserEntity userEntity){
        Map map = new HashMap();
        boolean data=userService.setUserData(userEntity);
        if (data){
            map.put("state",1);
            map.put("user",userService.selectUserOpenId(userEntity.getOpenId()));
            return map;
        }
        map.put("state",0);
        return map;
    }

    /**
     * 通过微信获取用户的手机号
     * @param code 微信登录时的code
     * @param encryptedData 手机号的加密字段
     * @param iv 加密字段的偏移
     * @return
     */
    @RequestMapping("/getPhone")
    @ResponseBody
    public Map getPhone(String code,String encryptedData,String iv){
        Map map = new HashMap();
        GetWeChat weChat = new GetWeChat();
        if(encryptedData==null || iv==null || encryptedData.equals(iv)){
            map.put("state",0);
            return map;
        }
        String phone=weChat.getWxPhone(code,encryptedData,iv);
        if (phone!=null || phone.length()>0){
            map.put("state",1);
            map.put("phone",phone);
        }
        return map;
    }

    /**
     * 搜索商品
     * @param search
     * @return
     */
    @RequestMapping("/searchProduct")
    @ResponseBody
    public Map searchProduct(String search){
        Map map = new HashMap();
        List<ProductNormEntity> productNormEntities = productNormService.searchProductNorm(search);
        JSON product = JSONArray.fromObject(productNormEntities);
        map.put("product",product);
        return map;
    }
    /**
     * 读取商品总表全部信息
     * @return
     */
    @RequestMapping("/getProductNorm")
    @ResponseBody
    public Map getProductNorm(){
        Map map = new HashMap();
        List<ProductNormEntity> productNormEntities = productNormService.selectProductNorm();
        JSON product = JSONArray.fromObject(productNormEntities);
        map.put("product",product);
        return map;
    }

    /**
     * 读取子商品
     * @param product_id
     * @return
     */
    @RequestMapping("/getNorm")
    @ResponseBody
    public Map getNorm(Integer product_id){
        Map map = new HashMap();
        List<NormEntity> normEntities = normService.normList(product_id);
        JSON norm = JSONArray.fromObject(normEntities);
        map.put("norm",norm);
        return map;
    }

    /**
     * 读取购物车
     * @param user_id
     * @return
     */
    @RequestMapping("/getCart")
    @ResponseBody
    public Map getCart(Integer user_id){
        Map map = new HashMap();
        List<CartEntity> cartEntities = cartService.selectCart(user_id);
        JSON cart = JSONArray.fromObject(cartEntities);
        map.put("cart",cart);
        return map;
    }

    @RequestMapping("/setCartNumber")
    @ResponseBody
    public Map setCartNumber(Integer id,Integer product_num){
        Map map = new HashMap();
        map.put("state",0);
        if(id!=null || product_num!=null){
            Boolean setCart = cartService.setCartNumber(product_num,id);
            if(setCart){
                map.put("state",1);
            }
        }
        return map;
    }

    @RequestMapping("/setOrder")
    @ResponseBody
    public Map setOrder(Integer user_id,String[] cart_ids){
        Map map = new HashMap();
        int row = cartService.setOrder(user_id,cart_ids);
        map.put("state",row);
        return map;
    }

    @RequestMapping("/wxPayOrder")
    @ResponseBody
    public Map<String, String> wxPayOrder(HttpServletRequest request) throws Exception {
        MyWXConfig config = new MyWXConfig();
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "购买商品");
        String out_trade_no = String.valueOf(UUID.next());
        data.put("out_trade_no", out_trade_no);//商户订单号
        data.put("total_fee", "1");
        data.put("spbill_create_ip", request.getRemoteAddr());
        data.put("notify_url", "127.0.0.1");
        data.put("trade_type", "JSAPI");  // 小程序支付
        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
